<template>
  <el-card style="height: 86vh">
    <el-col :span="2">
      <el-button type="primary" @click="onImportExcelClick">
        导入数据
      </el-button>
    </el-col>
  </el-card>
  <el-dialog v-model="UploadExcelDialogShow" title="上传数据">
    <el-upload
        class="upload-demo"
        multiple=""
        method="post"
        action="http://127.0.0.1:8882/yeKuo/uploadRecord"
        :headers="headers"
        style="margin-left: 10px"
        accept=".xlsx,.xls"
        :show-file-list="false"
        :on-progress="handleProgress"
        :on-success="handleSuccess"
        :on-error="handleError"
        :before-upload="beforeUploadHandle"
        :http-request="customUpload"
        name="files"
    >
      <el-button type="primary">导入</el-button>
    </el-upload>
  </el-dialog>
</template>
<script setup>
import utils from '@/utils/utils'
import { onMounted, ref } from 'vue'
import store from '@/store'
import axios from 'axios'

let headers = {}
const upLoadLoading = ref(false)
const UploadExcelDialogShow = ref(false)

const handleProgress = (file) => {
  upLoadLoading.value = true
}

const beforeUploadHandle = (file) => {
  utils.showLoadding('正在上传...')
  return true
}

const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('files', options.file)
    
    const response = await axios.post(options.action, formData, {
      headers: {
        ...headers,
        'Content-Type': 'multipart/form-data'
      },
      responseType: 'blob'
    })
    
    // 检查响应类型
    const contentType = response.headers['content-type']
    if (contentType && contentType.includes('application/json')) {
      // 如果是JSON响应，说明有错误
      const reader = new FileReader()
      reader.onload = () => {
        const result = JSON.parse(reader.result)
        utils.showError(result.msg || '上传失败')
      }
      reader.readAsText(response.data)
    } else {
      // 如果是Excel文件，触发下载
      const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = '业扩数据导入结果.xlsx'
      link.click()
      window.URL.revokeObjectURL(link.href)
      utils.showSuccess('处理完成，文件已下载')
    }
    
    UploadExcelDialogShow.value = false
    utils.hideLoadding()
  } catch (error) {
    utils.hideLoadding()
    utils.showError('上传失败：' + (error.message || '未知错误'))
  }
}

const handleSuccess = (res) => {
  // 由于使用了自定义上传，这个方法不会被调用
}

const handleError = (error) => {
  utils.hideLoadding()
  utils.showError('上传失败：' + (error.message || '未知错误'))
}

const onImportExcelClick = () => {
  UploadExcelDialogShow.value = true
}

onMounted(() => {
  headers = { 'X-Token': store.getters.token }
})
</script>